<template>
    <Modal v-model="visible" fullscreen  @on-visible-change="visibleChange">
        <p slot="header">
            <Icon type="logo-buffer" :size="22"/>
            <span style="margin-left: 0.5em">{{title}}</span>
        </p>
        <Row>
            <Col span="8">
                <Card dis-hover style="min-height: 500px">
                    <p slot="title">基本信息</p>
                    <Form ref="objectData" :disabled="!canEdit"  :model="objectData.role" :rules="ruleValidate" label-colon autocomplete="off"  :label-width="100">
                        <FormItem label="角色名称"  prop="roleName">
                          <label>
                            <Input v-model="objectData.role.roleName" clearable placeholder="请输入岗位名称"></Input>
                          </label>
                        </FormItem>
                        <FormItem label="角色描述"  prop="description">
                          <label>
                            <Input v-model="objectData.role.description" clearable placeholder="请输入岗位描述"></Input>
                          </label>
                        </FormItem>
                        <FormItem label="所属系统"  prop="systemCode">
                            <code-type-tag placeholder="请选择所属系统" code-type="systemCode" v-model="objectData.role.systemCode"/>
                        </FormItem>
                        <FormItem label="角色状态"  prop="valid">
                            <i-switch v-model="objectData.role.valid" :true-value="1" :false-value="0" size="large">
                                <span slot="open">正常</span>
                                <span slot="close">关闭</span>
                            </i-switch>
                        </FormItem>
                    </Form>
                </Card>
            </Col>
            <Col span="10">
                <Card dis-hover style="min-height: 500px">
                    <p slot="title">操作权限</p>
                    <Scroll height="400">
                        <Tree ref="permissionTree" :data="permissionTrees" show-checkbox @on-select-change="initDataSelectItem" empty-text="暂无权限数据" />
                    </Scroll>
                </Card>
            </Col>
          <Col span="6">
            <Card dis-hover style="min-height: 500px">
              <p slot="title">数据权限</p>
              <Scroll height="400">
                <Tree ref="dataPermissionTree" :data="dataPermissionTrees" show-checkbox empty-text="暂无权限数据" @on-check-change="singleChoiceHandle" />
              </Scroll>
            </Card>
          </Col>
        </Row>
        <div slot="footer" v-show="canEdit">
            <Button @click="cancel">取消</Button>
            <Button type="primary" @click="handleSubmit('objectData')">保存</Button>
        </div>
    </Modal>
</template>

<script>
    import {getUIPermission} from "@/api/permissionApi"
    import {getById,saveOrUpdate} from '@/api/roleApi'
    import {ruleValidate} from '@/views/settings/role/validator/RoleRules'
    import codeTypeTag from '@/components/codeType/code-type-tag'
    import RoleDataProvider from '@/views/settings/data/RoleDataProvider'
    export default {
        name: "role-details",
        components:{
            codeTypeTag
        },
        props:{
            showModal: {
                type: Boolean,
                required: true
            },
            canEdit: {
                type: Boolean,
                required: true
            },
            roleId:{
                type: [Number,String],
                required: false
            },
            title: {
                type: String,
                required: true,
            }
        },
        data () {
            return {
                visible: this.showModal,
                objectData: RoleDataProvider.createRoleVo(),
                ruleValidate,
                haveLoadData: false,
                permissionTrees: [],
                dataPermissionTrees: [],
                dataPermission: [],
            }
        },
        watch: {
            showModal (val) {
                this.visible = val
            },
            visible (val) {
              this.dataPermissionTrees = []
              if (val) {
                if (this.roleId){
                  this.haveLoadData = false
                  getById(this.roleId).then(res=>{
                    this.objectData = res;
                    if (res.role.systemCode){
                      getUIPermission(res.role.systemCode).then(res2=>{
                        this.permissionTrees = res2.viewPermission;
                        this.dataPermission = res2.dataPermission;
                        this.setSelectPermissionItem()
                        this.haveLoadData = true
                      })
                    }
                  })
                }else {
                  this.objectData = RoleDataProvider.createRoleVo()
                  this.permissionTrees = []
                  this.haveLoadData = true
                }
              }
            },
            'objectData.role.systemCode'(val){
                if (val&&this.haveLoadData){
                  getUIPermission(val).then(res=>{
                    this.dataPermissionTrees = []
                    this.permissionTrees = res.viewPermission
                    this.dataPermission = res2.dataPermission
                    this.setSelectPermissionItem()
                  })
                }
            }
        },
        methods: {
          handleSubmit(name) {
			  console.log(this.objectData.role.valid)
            this.$refs[name].validate((valid) => {
              if (valid) {
                let selectItems = this.$refs.permissionTree.getCheckedAndIndeterminateNodes()
                this.objectData.viewPermissionIds = []
                selectItems.forEach(item=>{
                  this.objectData.viewPermissionIds.push({id:item.id})
                })
                this.objectData.dataPermissionIds = this.getCheckedDataPermissionIds()
                let action = 'save';
                if (this.objectData.id){
                  action= 'update'
                }
                saveOrUpdate(this.objectData,action).then(res=>{
                  this.$Message.success(res)
                  this.visible = false
                  this.$emit('callbackByOk')
                })
              }
            })
          },
          cancel () {
            this.visible = false
          },
          visibleChange(val){
            if (!val){
              this.$emit('callbackByCancel')
            }
          },
          setSelectPermissionItem(){
            this.permissionTrees.forEach(permission => {
              this.objectData.viewPermissionIds.forEach(permissionId => {
                this.setCheckedOfPermissionTree(permission,permissionId.id)
              })
            })
            this.dataPermission.forEach(permission => {
              this.objectData.dataPermissionIds.forEach(permissionId => {
                this.setCheckedOfPermissionTree(permission,permissionId.id)
              })
            })
          },
          setCheckedOfPermissionTree(temp,permissionId){
            let needFind = true;
            while (needFind){
              temp.disableCheckbox = !this.canEdit;
              if (temp.id===permissionId){
                if (temp.children===null||temp.children===undefined){
                  temp.checked=true
                }
                needFind = false;
              }else if (temp.children) {
                temp.children.forEach(permission=>{
                  this.setCheckedOfPermissionTree(permission,permissionId);
                  needFind = false;
                })
              }else{
                needFind = false;
              }
            }
          },
          initDataSelectItem(nodes,node){
            let permission = this.dataPermission.filter(item=>(item.id === node.id));
            if (permission.length>0){
              this.dataPermissionTrees = permission[0].children
            }else{
              this.dataPermissionTrees =[]
            }
          },
          singleChoiceHandle(nodes,node){
            nodes.forEach(item=>{
              if (item.id!==node.id){
                item.checked= false;
              }
            });
          },
          getCheckedDataPermissionIds () {
            let dataPermissionIds = []
            this.dataPermission.forEach(item=>{
              if (item.children){
                item.children.forEach(child=>{
                  if (child.checked){
                    dataPermissionIds.push({id:child.id})
                  }
                })
              }
            })
            return dataPermissionIds;
          },
        }
    }
</script>

<style scoped>

</style>